﻿using HouseOfMystery.Filters;
using HouseOfMystery.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using WebMatrix.WebData;

namespace HouseOfMystery.Controllers
{
    [Authorize]
    public class RoomController : Controller
    {
        HouseDb db = new HouseDb();
        string currentId = WebSecurity.CurrentUserId.ToString();


        public ActionResult OpenRoom(int Id)
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

            // check if room is open
            // return appropriate view
            if (state != null && state.Rooms.ElementAt(Id).IsOpen)
            {
                return View("Room_" + Id);
            }

            return RedirectToAction("Index", "Home");
        }
                
        public void OpenLock(int Id)
        {
            if (GlobalVars.SelectedItem == "roomkey_" + Id)
            {
                UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

                state.Rooms.ElementAt(Id).IsOpen = true;
                db.SaveChanges();

                // remove key from items
                RemoveItem();
            }
        }

        public void RemoveItem()
        {
            UserState state = db.UserStates.FirstOrDefault(x => x.UserId == currentId);

            foreach (var item in state.Items)
            {
                if (item.Name == GlobalVars.SelectedItem)
                {
                    item.Name = null;
                    db.SaveChanges();

                    break;
                }
            }
        }
    }
}
